<template>
  <el-dialog
    v-model="visible"
    title="编辑待办事项"
    width="500px"
    :before-close="handleCancel"
  >
    <div class="todo-dialog-content">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="top"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入待办事项标题"
            maxlength="100"
            show-word-limit
            clearable
          />
        </el-form-item>
        
        <el-form-item label="日期" prop="date">
          <div class="date-selector">
            <div class="quick-dates">
              <el-button 
                v-for="dateOption in dateOptions"
                :key="dateOption.value"
                :type="form.date === dateOption.date ? 'primary' : 'default'"
                size="small"
                @click="handleDateSelect(dateOption)"
                class="date-btn"
              >
                {{ dateOption.label }}
              </el-button>
            </div>
            
            <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="date-picker"
            />
          </div>
        </el-form-item>
        
        <el-form-item label="时间">
          <el-time-select
            v-model="form.time"
            start="00:00"
            step="00:15"
            end="23:45"
            placeholder="选择时间（可选）"
            clearable
            class="time-picker"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch
            v-model="form.completed"
            active-text="已完成"
            inactive-text="待完成"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getToday, getTomorrow, getDayAfterTomorrow, formatDate } from '../utils/date'

export default {
  name: 'TodoDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    todo: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'save'],
  setup(props, { emit }) {
    const formRef = ref()
    const loading = ref(false)
    
    const visible = ref(false)
    
    const form = reactive({
      id: null,
      title: '',
      date: formatDate(getToday()),
      time: '',
      completed: false
    })
    
    const rules = {
      title: [
        { required: true, message: '请输入待办事项标题', trigger: 'blur' },
        { min: 1, max: 100, message: '标题长度应在 1 到 100 个字符', trigger: 'blur' }
      ],
      date: [
        { required: true, message: '请选择日期', trigger: 'change' }
      ]
    }
    
    const dateOptions = [
      {
        label: '今天',
        value: 'today',
        date: formatDate(getToday())
      },
      {
        label: '明天',
        value: 'tomorrow',
        date: formatDate(getTomorrow())
      },
      {
        label: '后天',
        value: 'dayAfterTomorrow',
        date: formatDate(getDayAfterTomorrow())
      }
    ]
    
    // 监听 modelValue 变化
    watch(() => props.modelValue, (newVal) => {
      visible.value = newVal
      if (newVal && props.todo) {
        // 编辑模式，填充表单数据
        form.id = props.todo.id
        form.title = props.todo.title
        form.date = props.todo.dueDate
        form.time = props.todo.dueTime || ''
        form.completed = props.todo.completed || false
      } else if (newVal) {
        // 新增模式，重置表单
        form.id = null
        form.title = ''
        form.date = formatDate(getToday())
        form.time = ''
        form.completed = false
      }
    })
    
    // 监听 visible 变化
    watch(visible, (newVal) => {
      emit('update:modelValue', newVal)
    })
    
    const handleDateSelect = (dateOption) => {
      form.date = dateOption.date
    }
    
    const handleCancel = () => {
      visible.value = false
      formRef.value?.resetFields()
    }
    
    const handleSave = async () => {
      try {
        const valid = await formRef.value?.validate()
        if (!valid) return
        
        loading.value = true
        
        const todoData = {
          id: form.id,
          title: form.title.trim(),
          dueDate: form.date,
          dueTime: form.time || null,
          completed: form.completed
        }
        
        await emit('save', todoData)
        
        visible.value = false
        formRef.value?.resetFields()
        
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      } finally {
        loading.value = false
      }
    }
    
    return {
      formRef,
      loading,
      visible,
      form,
      rules,
      dateOptions,
      handleDateSelect,
      handleCancel,
      handleSave
    }
  }
}
</script>

<style scoped>
.todo-dialog-content {
  padding: 16px 0;
}

.date-selector {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.quick-dates {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.date-btn {
  padding: 6px 12px;
  font-size: 12px;
}

.date-picker {
  width: 100%;
}

.time-picker {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

::v-deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

::v-deep(.el-dialog__header) {
  padding: 20px 20px 0 20px;
}

::v-deep(.el-dialog__body) {
  padding: 20px;
}

::v-deep(.el-dialog__footer) {
  padding: 0 20px 20px 20px;
}
</style> 